<template>
  <div class="search-container">
    <form action="/">
      <van-search
        background="#3296fa"
        v-model="searchVal"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @input="onInput"
        @cancel="onCancel"
        @focus="onFocus"
      />
    </form>
    <!-- /搜索栏 -->
        <!-- 搜索结果 -->
    <search-result  :searchVal='searchVal'  v-if="showCom" />
    <!-- /搜索结果 -->
    <!-- 联想建议 -->
    <search-suggestion  @search="onSearch" :searchVal='searchVal' v-else-if="searchVal"/>
    <!-- /联想建议 -->
   <!-- 搜索历史记录 -->
    <search-history @search="onSearch" @delAllHis='historyVal=[]' :historyVal='historyVal' v-else />
    <!-- /搜索历史记录 -->
  </div>
</template>
           
<script>
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'

import { SET_TOKEN, GET_TOKEN } from '@/utils/storage.js'


export default {
  data() {
    return {
      searchVal: '',
      showCom: false,
      historyVal: GET_TOKEN('historyVal')||[],
      
    }
  },
  methods: {
    async onSearch(val) {
       this.searchVal = val
      console.log(val,123333333);
      /* 
      回车：将值存入到本地缓存中，并且可以显示在history组件中
      */
      //this.searchVal.unshift()
      /* 
      var  arr=[1,2,3]   1
      
      */
     // 输入值匹配并删除  
        var  index=this.historyVal.findIndex(item=>{
          return item==val
        })
        if(index!=-1){
          this.historyVal.splice(index,1)
        }

        this.historyVal = [val, ...this.historyVal]

      SET_TOKEN('historyVal',this.historyVal)

      this.$toast(val)
      this.showCom = true
      

      

    },
    onCancel() {
      //this.$toast('取消')
      this.$router.go(-1)
    },
    onInput() {
      console.log(111)
      this.showCom = false
    },
    onFocus(){
      this.showCom=false
    }
  },
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  }
}
</script>
<style scoped   lang='less'>
.search-container {
  padding-top: 100px;
  form {
    position: fixed;
    top: 0;
    width: 100%;
    z-index:999;
    /deep/.van-search__action {
      color: #fff;
    }
  }
}
</style>